package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProduct;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductFeignApi;
import cn.wolfcode.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.List;
import java.util.Set;

@Component
@Setter
@Getter
@RefreshScope
@Slf4j
public class MyInitSeckillProductJob implements SimpleJob {

    @Value("${jobCron.initSeckillProduct}")
    private String cron;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SeckillProductFeignApi  seckillProductFeignApi;


    public void execute(ShardingContext shardingContext) {
//        System.out.println(shardingContext.getShardingParameter());
        doWork(shardingContext.getShardingParameter());
    }

    private void doWork(String time) {

        //三个情况

        Result<List<SeckillProductVo>> listResult = seckillProductFeignApi.selectByTime(Integer.parseInt(time));
        if (listResult!=null && !listResult.hasError()){
            //正确 调用redis
            List<SeckillProductVo> data = listResult.getData();
            if (data != null && data.size() > 0){
                for (SeckillProductVo datum : data) {
                    redisTemplate.opsForHash().put(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(time),datum.getId()+"", JSON.toJSONString(datum));
                    redisTemplate.opsForHash().put(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time),datum.getId()+"", datum.getStockCount()+"");
                }
            }
        }


    }

}
